package com.hospital.interceptor;

import com.hospital.entity.User;
import com.hospital.util.JwtUtil;
import com.hospital.util.UserContext;
import com.hospital.exception.TokenException;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * JWT认证拦截器
 *
 * @author Hospital Management System
 */
@Slf4j
@Component
@RequiredArgsConstructor
public class JwtAuthInterceptor implements HandlerInterceptor {

    private final JwtUtil jwtUtil;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        // 获取Authorization头
        String authHeader = request.getHeader("Authorization");
        
        // 检查是否存在token
        if (authHeader == null || !authHeader.startsWith("Bearer ")) {
            throw new TokenException("未提供有效的认证信息");
        }
        
        // 获取token
        String token = authHeader.substring(7);
        
        try {
            // 验证token
            if (!jwtUtil.validateToken(token)) {
                throw new TokenException("无效的token");
            }
            
            // 从token中获取用户信息
            Long userId = jwtUtil.getUserIdFromToken(token);
            String username = jwtUtil.getUsernameFromToken(token);
            Integer role = jwtUtil.getRoleFromToken(token);
            
            // 创建用户对象并设置上下文
            User user = new User();
            user.setId(userId);
            user.setUsername(username);
            user.setRole(role);
            
            UserContext.setCurrentUser(user);
            return true;
        } catch (Exception e) {
            log.warn("Token验证失败: {}", e.getMessage());
            throw new TokenException("登录已过期，请重新登录", e);
        }
    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) {
        // 清理用户上下文
        UserContext.clear();
    }
} 